import Vue from 'vue'
import router from './router'
import store from './store'
import App from './App'

let instance = null
// const appName = 'cd'
const init = (appName) => {
  if (!window.isInFramework) {
    console.log('子应用独立运行（整个项目仅执行一次）')
    Vue.prototype.bus = new Vue()
    instance = new Vue({
      el: '#app',
      router,
      store,
      render: h => h(App)
    })
  }
  async function bootstrap() {
    console.log(`${appName} app bootstraped`)

  }

  async function mount(props) {
    console.log(`${appName} props mount -> `, props)
    if (!instance) {
      Vue.prototype.bus = props.frkInstance
      Vue.prototype.$frkInstance = props.frkInstance
      Vue.prototype.$isInFramework = props.isInFramework
      instance = new Vue({
        router,
        store,
        data: {
          isInFramework: false
        },
        render: h => h(App)
      }).$mount()
    }
    // console.log('frk->', instance.$frkInstance)
    props.appCallback(instance) // 主框架中的回调函数，用于将子应用的实列传到主框架
    instance.isInFramework = props.isInFramework
    const parent = document.getElementById('app').parentElement
    parent.replaceChild(instance.$el, parent.querySelector('#app'))
  }

  async function unmount() {
    console.log(`${appName} unmount`)
    // instance.$router.beforeHooks.splice(0, instance.$router.beforeHooks.length)
  }

  return {
    bootstrap,
    mount,
    unmount
  }
}

export default init
